<?php
namespace app\home\controller;
use think\Controller;
use think\Db;
/**
 * @title 注册/登陆
 * @description 接口说明
 * @group 后台管理
 */
class Login extends Controller{
    /**
     * @title 登陆
     * @description 接口说明
     * @author lonnie
     * @url /home/login/douserLogin
     * @method POST
     *
     * @param name:username type:string require:1 default:1 other: desc:用户名
     * @param name:password type:string require:1 default:1 other: desc:密码
     */
    public function douserLogin()
    {

        $params = input();
        $username = !empty($params['username']) ? $params['username'] : '';
        $password = !empty($params['password']) ? $params['password'] : '';

        if(empty($username) || empty($password)){
            return json(['code' => 1,'msg' => '参数错误']);
        }

        //$user_map['name'] = ['eq',$username];
        $user_map['password'] = ['eq',md5($password.config('salt'))];
        $user_map['status'] = ['eq',0];
        $user_map['deleted'] = ['eq',0];

        //$count = $user->getCount($user_map);
        $info = Db::name('user')->where(function ($query) use ($username,$password,$user_map) {
            $query->where('name',$username)->where($user_map)->whereOr(function ($query) use ($username,$password,$user_map){
                $query->where('mobile',$username)->where($user_map);
            });
        })->where($user_map)->find();

        if (empty($info)) {
            return json(['code' => 1,'msg' => '用户不存在或密码错误']);
        } else {
            if($info['status'] == 1){
                return json(['code' => 1,'msg' => '该人员已被禁用，请联系管理员！']);
            }

            //定义一个常量，后面方便使用
            $time_out = time() + 3600 * 12;
            $token = $this->makeToken($info,$time_out);

            session('time_out',$time_out);
            define ('USER_ID',$info["id"]);
            define ('USER_NAME',$info["name"]);
            $menu = $this->menu($info['isadmin']);
            $node = $this->node($info['isadmin']);

            //登陆日志
            //$log['dept'] = $info["deptid"];
            //$log['userid'] = $info["id"];
            //$log['logintime'] = date('Y-m-d H:i:s');
            //$log['ispc'] = 1;
            //$add_logs = Db::table('hs_user_logs')->insert($log);
            return json([
                'code' => 0,
                'msg' => '登录成功',
                'data'=>[
                    'token' => $token,
                    'username'=>$username,
                    'name' => $info["name"],
                    'dept' => $info["deptid"],
                    'menu' => $menu,
                    'node' => $node,
                    'headImg' => $info['headImg'],
                ]
            ]);
        }
    }

    //生成加密token值
    private function makeToken($info,$time_out)
    {
        $str = json_encode(array("userid"=>$info['id'],'mobile' => $info['mobile'],'isadmin' => $info['isadmin'],'dept' => $info['deptid'],'time_out' => $time_out,'name' => $info["name"]));
        return encode($str);  //对称加密
    }

    /**
     * @title 注册
     * @description 接口说明
     * @author lonnie
     * @url /home/login/register
     * @method POST
     *
     * @param name:name type:string require:1 default:1 other: desc:用户名
     * @param name:mobile type:string require:1 default:1 other: desc:用户名
     * @param name:password type:string require:1 default:1 other: desc:密码
     *
     */
    public function register(){
        $params = input();
        Db::startTrans();
        $name = !empty($params['name']) ? $params['name'] : '';
        $mobile = !empty($params['mobile']) ? $params['mobile'] : '';
        $deptid = !empty($params['deptid']) ? $params['deptid'] : 0;
        $password = !empty($params['password']) ? $params['password'] : '';
        $repassword = !empty($params['repassword']) ? $params['repassword'] : '';
        if(!$name){
            return json(['code' => 1,'msg' => '请填写用户名']);
        }
        if(!$mobile){
            return json(['code' => 1,'msg' => '请填写手机号']);
        }
        if(!is_mobile($mobile)){
            return json(['code' => 1,'msg' => '不是正确的手机号']);
        }
        if(!$password){
            return json(['code' => 1,'msg' => '请填写密码']);
        }
        if(!$repassword){
            return json(['code' => 1,'msg' => '请填写确认密码']);
        }
        if($repassword !== $password){
            return json(['code' => 1,'msg' => '两次填写的密码不一致']);
        }


        $user_map['mobile'] = ['eq',$mobile];
        //$user_map['deleted'] = ['eq',0];
        $have = Db::name('user')->where($user_map)->count();
        if($have){
            return json(['code' => 1,'msg' => '当前手机号已经存在']);
        }

        $res['name'] = $name;
        $res['mobile'] = $mobile;
        $res['password'] = md5($params['password'].config('salt'));
        $res['deptid'] = $deptid;
        $res['ctime'] = date('Y-m-d H:i:s');
        $res['isadmin'] = 0;
        $add_user = Db::name('user')->insert($res);
        if($add_user){
            Db::commit();
            return json(['code' => 0,'msg' => '注册成功']);
        }else{
            Db::rollback();
            return json(['code' => 1,'msg' => '注册失败']);
        }
    }

    /**
     * 方法名：menu
     * 方法说明 左侧菜单
     */
    public function menu($isadmin=false){
        $map['fid'] = ['neq',0];
        $map['ismenu'] = ['eq',1];
        $map['isshow'] = ['eq',1];
        $map['deleted'] = ['eq',0];
        $rule = new \app\home\model\Authrule();
        $list = $rule->lst($map);

        $auth = new \auth\Auth();
        $data = array_flip($auth->getids(USER_ID));
        foreach($list as $key=>$val){
            if($isadmin){
                //$list[$key]["name"]=url($list[$key]["name"]);
            }else{
                if(isset($data[$val['id']])){
                    //$list[$key]["name"]=url($list[$key]["name"]);
                }else{
                    unset($list[$key]);
                }
            }
        }
        $menus = [];
        foreach ($list as $k => $v){
            $menus[] = $v['id'];
        }

        $data = $rule->FixNode($list,1);
        return $data;
    }

    public function node($isadmin = false){
        $map['fid'] = ['neq',0];
        $map['isshow'] = ['eq',1];
        $map['ismenu'] = ['eq',0];   //不是菜单
        $rule = new \app\home\model\Authrule();
        $list = $rule->lst($map);

        $auth = new \auth\Auth();
        $data = array_flip($auth->getids(USER_ID));
        $node = [];
        foreach($list as $key=>$val){
            if($isadmin){
                //超级管理员
                if($val['name']){
                    $node_name = str_replace("/","_",$val['name']);
                    $node[$node_name] = true;
                }
                //$list[$key]["name"]=url($list[$key]["name"]);
            }else{
                if($val['name']){
                    $node_name = str_replace("/","_",$val['name']);
                    if(isset($data[$val['id']])){
                        $node[$node_name] = true;
                        //$list[$key]["name"]= url($list[$key]["name"]);
                    }else{
                        $node[$node_name] = false;
                        //unset($list[$key]);
                    }
                }
            }
        }

        return $node;
    }
}